package com.simpleframe.core.io;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URISyntaxException;
import java.net.URL;

import com.simpleframe.util.Assert;
import com.simpleframe.util.ClassUtil;

public class WebPathResource extends AbstractResource {
	
	String path;
	
	File file;
	
	ClassLoader classLoader;
	
	/**
	 * web 文件路径必须以 / 开始
	 * @param path
	 */
	public WebPathResource(String path){
		this(path, (ClassLoader)null);
	}
	
	public WebPathResource(String path, ClassLoader classLoader){
		Assert.notNull(path, "path 不能为空");
		if (path.indexOf("/") != 0){
			throw new IllegalArgumentException("路径 "+path+" 必须以 / 开始");
		}
		if(classLoader==null){
			this.classLoader = ClassUtil.getDefaultClassLoader();
		}

		String result = getAbsolutePathOfWebRoot() + path.replace('/', File.separatorChar);
		
		this.file = new File(result);
		
		this.path = path;
	}
	
	@Override
	public InputStream getInputStream(){
		try {
			return new FileInputStream(this.file);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	@Override
	public URL getURL(){
		try {
			return this.file.toURI().toURL();
		} catch (MalformedURLException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	@Override
	public File getFile(){
		return this.file;
	}
	
	/////////////////////////////
	
	// 得到WebRoot目录的绝对地址
    private String getAbsolutePathOfWebRoot() {
        String result = null;
        result = getAbsolutePathOfClassPath();
        result = result.replace(File.separatorChar + "WEB-INF"
                + File.separatorChar + "classes", "");
        return result;
    }

    // 得到ClassPath的绝对路径
    private String getAbsolutePathOfClassPath() {
        String result = null;
        try {
            File file = new File(getURLOfClassPath().toURI());
            result = file.getAbsolutePath();
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
        return result;
    }

    // 得到ClassPath的URL
    private URL getURLOfClassPath() {
        return classLoader.getResource("");
    }
	
	public static void main(String[] args) throws IOException {
		WebPathResource webPathResource = new WebPathResource("/test.xml");
		System.out.println(webPathResource.getFile());
	}
}
